<template>
  <van-sticky>
    <van-nav-bar
        :title="title"
        left-arrow
        @click-left="onClickLeft"
    >
    </van-nav-bar>
  </van-sticky>
  <div class="chat-container">
    <div class="content" ref="chatRoom">
      <div v-for="(message, index) in stats.messages" :key="index" 
           :class="['message', message.isMy ? 'self' : 'other']">
        <!-- 对方的消息 -->
        <template v-if="!message.isMy">
          <img :alt="message.fromUser?.username || '对方'" class="avatar" 
               :src="processImageUrl(message.fromUser?.avatarUrl || '/src/assets/defaultAvatar.png')" 
               @click="showUser(message.fromUser?.id || 0)">
          <div class="info">
            <span class="username">
              {{ (message.fromUser?.username || '对方').length < 10 ? 
                 (message.fromUser?.username || '对方') : 
                 (message.fromUser?.username || '对方').substring(0, 10) + '...' }}
              &nbsp;&nbsp;&nbsp;{{ message.createTime }}
            </span>
            <p :class="[message.isAdmin ? 'admin text' : 'text']">{{ message.text }}</p>
          </div>
        </template>
        
        <!-- 自己的消息 -->
        <template v-else>
          <div class="info right-content">
            <span class="username right-align">{{ message.createTime }}</span>
            <p class="text">{{ message.text }}</p>
          </div>
          <img :alt="message.fromUser?.username || '我'" class="avatar self-avatar" 
               :src="processImageUrl(message.fromUser?.avatarUrl || '/src/assets/defaultAvatar.png')" 
               @click="showUser(message.fromUser?.id || stats.value.user.id)">
        </template>
      </div>
    </div>
    <div class="input-area">
      <van-field
          v-model="stats.text"
          center
          clearable
          placeholder="聊点什么吧...."
          @keydown.enter="send">
        <template #button>
          <van-button size="small" type="primary" @click="send">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {showFailToast} from "vant";

import {getCurrentUser} from "../../services/user.ts";
import myAxios, {URL} from "../../plugins/myAxios.ts";
import {processImageUrl} from '../../utils/imageUtils';

const route = useRoute();
const router = useRouter();
const stats = ref({
  user: {
    id: 0,
    username: "",
    avatarUrl: ''
  },
  isCollapse: false,
  users: [],
  chatUser: {
    id: 0,
    username: ''
  },
  chatEnum: {
    // 私聊
    PRIVATE_CHAT: 1,
    // 队伍聊天
    TEAM_CHAT: 2,
    // 大厅
    HALL_CHAT: 3
  },
  chatType: null,
  team: {
    teamId: 0,
    teamName: ''
  },
  text: "",
  messages: [],
  content: '',
  reconnectAttempts: 0
})

let socket = null;
const heartbeatInterval = 30 * 1000; // 30秒
let heartbeatTimer = null;

const startHeartbeat = () => {
  heartbeatTimer = setInterval(() => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send("PING");
    }
  }, heartbeatInterval);
}

const stopHeartbeat = () => {
  clearInterval(heartbeatTimer);
  heartbeatTimer = null;
}

const chatRoom = ref(null)
const DEFAULT_TITLE = "聊天"
const title = ref(DEFAULT_TITLE)

onMounted(async () => {
  let {id, username, userType, teamId, teamName, teamType} = route.query
  stats.value.chatUser.id = Number.parseInt(id)
  stats.value.team.teamId = Number.parseInt(teamId)
  stats.value.chatUser.username = username
  stats.value.team.teamName = teamName
  
  if (userType && Number.parseInt(userType) === stats.value.chatEnum.PRIVATE_CHAT) {
    stats.value.chatType = stats.value.chatEnum.PRIVATE_CHAT
    title.value = stats.value.chatUser.username
    
    // 获取聊天对象的完整信息
    try {
      const chatUserResponse = await myAxios.get(`/user/get/id?id=${stats.value.chatUser.id}`);
      if (chatUserResponse.code === 0 && chatUserResponse.data) {
        stats.value.chatUser = chatUserResponse.data;
        title.value = stats.value.chatUser.username;
        console.log('已获取聊天对象完整信息:', stats.value.chatUser);
      }
    } catch (error) {
      console.error('获取聊天对象信息失败:', error);
    }
  } else if (teamType && Number.parseInt(teamType) === stats.value.chatEnum.TEAM_CHAT) {
    stats.value.chatType = stats.value.chatEnum.TEAM_CHAT
    title.value = stats.value.team.teamName
  } else {
    stats.value.chatType = stats.value.chatEnum.HALL_CHAT
    title.value = "公共聊天室"
  }
  
  const userResponse = await getCurrentUser();
  stats.value.user = userResponse.data;
  
  // 清空当前消息列表
  stats.value.messages = [];
  
  // 获取消息
  let messages = [];
  
  // 私聊
  if (stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
    try {
      console.log('开始请求私聊历史消息...');
      console.log('请求参数:', {
        teamId: '',
        toId: stats.value.chatUser.id,
      });
      
      const privateMessage = await myAxios.post("/chat/privateChat", {
        teamId: '',
        toId: stats.value.chatUser.id,
      });
      console.log('私聊历史消息请求返回:', privateMessage);
      
      if (privateMessage && privateMessage.code === 0) {
        if (privateMessage.data && Array.isArray(privateMessage.data) && privateMessage.data.length > 0) {
          messages = privateMessage.data;
          console.log('获取到私聊历史消息数量:', messages.length);
          
          // 记录每条消息的详细信息，便于调试
          const sampleMessage = messages[0];
          console.log('示例消息结构:', JSON.stringify(sampleMessage, null, 2));
          console.log('字段列表:', Object.keys(sampleMessage).join(', '));
          console.log('时间格式示例:', sampleMessage.createTime);
          
          // 检查消息是否有必要的字段
          const requiredFields = ['fromId', 'toId', 'text', 'createTime'];
          const missingFields = [];
          requiredFields.forEach(field => {
            if (sampleMessage[field] === undefined) {
              missingFields.push(field);
            }
          });
          
          if (missingFields.length > 0) {
            console.warn('消息缺少必要字段:', missingFields.join(', '));
          }
          
          // 确保每个消息都有正确的时间格式
          messages.forEach((msg, index) => {
            if (!msg.createTime) {
              console.warn(`消息 ${index} 缺少时间, 使用当前时间替代`);
              const now = new Date();
              const year = now.getFullYear();
              const month = now.getMonth() + 1;
              const day = now.getDate();
              const hour = now.getHours().toString().padStart(2, '0');
              const minute = now.getMinutes().toString().padStart(2, '0');
              const second = now.getSeconds().toString().padStart(2, '0');
              msg.createTime = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
            }
          });
        } else {
          console.log('没有历史私聊消息或返回数据格式不正确');
          console.log('返回数据:', privateMessage.data);
          messages = [];
        }
      } else {
        console.warn('获取私聊历史消息失败或返回为空:', privateMessage);
        messages = [];
      }
    } catch (error) {
      console.error('获取私聊消息时出错:', error);
      console.error('错误详情:', error.message, error.stack);
      showFailToast('获取聊天历史失败，但您仍可发送新消息');
      messages = [];
    }
  } 
  // 大厅聊天
  else if (stats.value.chatType === stats.value.chatEnum.HALL_CHAT) {
    const hallMessage = await myAxios.get("/chat/hallChat");
    if (hallMessage.data) {
      messages = hallMessage.data;
      console.log('获取到大厅聊天消息:', messages);
    }
  }
  // 队伍聊天
  else if (stats.value.chatType === stats.value.chatEnum.TEAM_CHAT) {
    const teamMessage = await myAxios.post("/chat/teamChat", {
      teamId: stats.value.team.teamId
    });
    if (teamMessage.data) {
      messages = teamMessage.data;
      console.log('获取到队伍聊天消息:', messages);
    }
  }
  
  // 统一处理所有消息
  if (messages && messages.length > 0) {
    // 克隆消息数组以避免修改原始数据
    const processedMessages = JSON.parse(JSON.stringify(messages));
    
    // 如果是私聊，对消息进行预处理
    if (stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
      // 记录当前用户ID用于消息判断
      const currentUserId = stats.value.user.id;
      console.log('当前用户ID:', currentUserId);
      
      // 确保每条消息都有正确的发送方标识
      processedMessages.forEach((msg, index) => {
        // 直接使用后端返回的isMy标志，如果有的话
        if (msg.isMy !== undefined) {
          console.log(`消息${index + 1} 使用后端isMy标志:`, msg.isMy);
        } 
        // 如果没有isMy标志，通过fromId判断
        else if (msg.fromId !== undefined) {
          msg.isMy = (Number(msg.fromId) === Number(currentUserId));
          console.log(`消息${index + 1} 通过fromId判断isMy: fromId=${msg.fromId}, currentUserId=${currentUserId}, isMy=${msg.isMy}`);
        }
        // 如果都没有，通过fromUser判断
        else if (msg.fromUser && msg.fromUser.id !== undefined) {
          msg.isMy = (Number(msg.fromUser.id) === Number(currentUserId));
          console.log(`消息${index + 1} 通过fromUser.id判断isMy: fromUserId=${msg.fromUser.id}, currentUserId=${currentUserId}, isMy=${msg.isMy}`);
        }
        
        // 确保消息有fromUser对象
        if (!msg.fromUser) {
          if (msg.isMy) {
            msg.fromUser = { ...stats.value.user };
            console.log(`消息${index + 1} 添加当前用户作为fromUser`);
          } else {
            msg.fromUser = { ...stats.value.chatUser };
            console.log(`消息${index + 1} 添加聊天对象作为fromUser`);
          }
        }
        
        console.log(`消息${index + 1} 最终处理结果:`, {
          isMy: msg.isMy,
          fromId: msg.fromId,
          toId: msg.toId,
          fromUser: msg.fromUser ? msg.fromUser.id : 'undefined'
        });
      });
    }
    
    // 构建一个有序消息数组
    const orderedMessages = [];
    processedMessages.forEach(msg => {
      // 在构建过程中直接按时间顺序插入
      insertMessageIntoArray(msg, orderedMessages);
    });
    
    console.log('按时间排序后的所有消息数量:', orderedMessages.length);
    
    // 设置排序后的消息列表
    stats.value.messages = orderedMessages;
  } else {
    console.log('没有历史消息可显示');
    stats.value.messages = [];
  }
  
  init();
  await nextTick();
  scrollToBottom();
});

const init = () => {
  let uid = stats.value.user?.id;
  if (!uid) {
    showFailToast("用户未登录")
    return;
  }
  
  if (typeof (WebSocket) == "undefined") {
    showFailToast("您的浏览器不支持WebSocket")
    return;
  }
  
  try {
    // 构建WebSocket URL
    let socketUrl;
    if (stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
      // 私聊
      socketUrl = `${URL.WEBSOCKET}/api/websocket/${uid}/${stats.value.chatUser.id}`;
      console.log('初始化私聊 WebSocket:', { 
        uid, 
        chatUserId: stats.value.chatUser.id,
        chatUserName: stats.value.chatUser.username
      });
    } else if (stats.value.chatType === stats.value.chatEnum.TEAM_CHAT) {
      // 队伍聊天
      socketUrl = `${URL.WEBSOCKET}/api/websocket/${uid}/${stats.value.team.teamId}`;
      console.log('初始化队伍聊天 WebSocket:', { 
        uid, 
        teamId: stats.value.team.teamId,
        teamName: stats.value.team.teamName
      });
    } else {
      // 大厅聊天
      socketUrl = `${URL.WEBSOCKET}/api/websocket/${uid}/0`;
      console.log('初始化大厅聊天 WebSocket:', { uid });
    }
    
    console.log('连接WebSocket:', socketUrl);
    console.log('WebSocket基础URL:', URL.WEBSOCKET);
    
    // 关闭已有连接
    if (socket != null) {
      console.log('关闭之前的WebSocket连接');
      socket.close();
      socket = null;
    }
    
    // 开启websocket服务
    socket = new WebSocket(socketUrl);
    
    // 设置连接超时
    const connectionTimeout = setTimeout(() => {
      if (socket && socket.readyState !== WebSocket.OPEN) {
        console.log('WebSocket连接超时，尝试使用备用连接方式');
        
        if (socket) {
          socket.close();
        }
        
        // 备用连接方式 - 尝试通过HTTP代理连接
        let backupUrl;
        // 尝试使用和API相同的端口
        const httpProxyAddress = 'ws://47.109.146.201:6100';
        
        if (stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
          backupUrl = `${httpProxyAddress}/api/websocket/${uid}/${stats.value.chatUser.id}`;
        } else if (stats.value.chatType === stats.value.chatEnum.TEAM_CHAT) {
          backupUrl = `${httpProxyAddress}/api/websocket/${uid}/${stats.value.team.teamId}`;
        } else {
          backupUrl = `${httpProxyAddress}/api/websocket/${uid}/0`;
        }
        
        console.log('尝试HTTP代理直连:', backupUrl);
        socket = new WebSocket(backupUrl);
        
        // 重新绑定事件处理器
        setupSocketEventHandlers(socket);
      }
    }, 5000);
    
    // 设置事件处理器
    setupSocketEventHandlers(socket);
    
    // 清除超时计时器（如果连接成功）
    socket.addEventListener('open', () => {
      clearTimeout(connectionTimeout);
      console.log('WebSocket连接成功，清除超时计时器');
      
      // 发送一个空消息，确保连接是活跃的
      if (stats.value.chatType === stats.value.chatEnum.HALL_CHAT || 
          stats.value.chatType === stats.value.chatEnum.TEAM_CHAT) {
        console.log('发送测试消息确认连接活跃');
        socket.send("PING");
      }
    });
  } catch (error) {
    console.error('初始化WebSocket失败:', error);
    console.error('错误详情:', error.message, error.stack);
    showFailToast('聊天连接失败，请刷新页面重试');
  }
}

// 设置WebSocket事件处理器
const setupSocketEventHandlers = (ws) => {
  // 接收消息事件
  ws.onmessage = function(msg) {
    if (msg.data === "pong") {
      console.log('收到服务器心跳响应: pong');
      return;
    }
    
    try {
      // 解析JSON数据
      let data = JSON.parse(msg.data)
      console.log('收到WebSocket消息:', data);
      
      if (data.error) {
        showFailToast(data.error)
        return;
      }
      
      // 获取在线人员信息
      if (data.users) {
        stats.value.users = data.users.filter(user => {
          return user.id !== stats.value.user.id
        })
        // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
        return;
      }
      
      // 获取当前用户ID
      const currentUserId = stats.value.user.id;
      
      // 处理聊天消息 - 确定是否应该显示此消息
      let shouldDisplay = false;
      
      // 记录聊天类型，确保数字比较
      const msgChatType = Number(data.chatType);
      const currentChatType = Number(stats.value.chatType);
      
      console.log('聊天类型对比:', { 
        msgChatType, 
        currentChatType, 
        isPrivateChat: currentChatType === stats.value.chatEnum.PRIVATE_CHAT 
      });
      
      if (currentChatType === stats.value.chatEnum.PRIVATE_CHAT && currentChatType === msgChatType) {
        // 私聊消息 - 确保是与当前聊天对象的对话
        const fromId = Number(data.fromId);
        const toId = Number(data.toId);
        const myId = Number(currentUserId);
        const chatUserId = Number(stats.value.chatUser.id);
        
        shouldDisplay = (
          // 对方发给我的消息
          (myId === toId && chatUserId === fromId) ||
          // 我发给对方的消息
          (myId === fromId && chatUserId === toId)
        );
        
        // 设置消息的isMy标志
        data.isMy = (fromId === myId);
        
        console.log('私聊消息检查:', { 
          shouldDisplay, 
          toId, 
          myId, 
          fromId, 
          chatUserId,
          isMy: data.isMy
        });
      } else if (currentChatType === stats.value.chatEnum.HALL_CHAT && msgChatType === stats.value.chatEnum.HALL_CHAT) {
        // 大厅聊天 - 显示所有消息
        shouldDisplay = true;
        console.log('大厅聊天消息检查:', { shouldDisplay, fromId: data.fromId, myId: currentUserId });
      } else if (currentChatType === stats.value.chatEnum.TEAM_CHAT && msgChatType === stats.value.chatEnum.TEAM_CHAT) {
        // 队伍聊天 - 确保是当前队伍的消息
        shouldDisplay = (data.teamId && Number(stats.value.team.teamId) === Number(data.teamId));
        console.log('队伍聊天消息检查:', { shouldDisplay, teamId: data.teamId, myTeamId: stats.value.team.teamId });
      }
      
      console.log('消息显示判断:', { shouldDisplay, chatType: currentChatType, msgChatType });
      
      if (shouldDisplay) {
        // 如果消息是自己发的，跳过显示（因为发送时已经显示了）
        if (Number(data.fromId) === Number(currentUserId)) {
          console.log('跳过显示自己发送的消息，因为发送时已经显示');
          return;
        }
        
        // 确保有发送者信息
        if (!data.fromUser) {
          if (stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
            // 如果是私聊且没有发送者信息，使用聊天对象信息
            data.fromUser = { ...stats.value.chatUser };
            console.log('使用聊天对象信息作为发送者:', data.fromUser);
          } else {
            // 默认创建一个基本用户对象
            data.fromUser = {
              id: data.fromId,
              username: '用户' + data.fromId,
              avatarUrl: '/src/assets/defaultAvatar.png'
            };
            console.log('创建默认发送者信息:', data.fromUser);
          }
        }
        
        // 创建消息对象
        const messageWithTime = {
          ...data,
          createTime: data.createTime || new Date().toLocaleString(),
          isMy: false // 收到的消息一定是对方发的
        };
        
        // 按时间顺序插入消息
        insertMessageInOrder(messageWithTime);
        
        // 滚动到底部
        nextTick(() => {
          scrollToBottom();
        });
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error);
      console.error('消息内容:', msg.data);
    }
  };
  
  // 关闭事件
  ws.onclose = function (event) {
    console.log('WebSocket连接已关闭, 代码:', event.code, '原因:', event.reason || '未知');
    stopHeartbeat();
    
    // 增加重连延迟和次数限制
    const maxRetries = 5;
    const retryDelay = 5000;
    
    if (!stats.value.reconnectAttempts) {
      stats.value.reconnectAttempts = 0;
    }
    
    if (stats.value.reconnectAttempts < maxRetries) {
      stats.value.reconnectAttempts++;
      console.log(`尝试第 ${stats.value.reconnectAttempts} 次重新连接，将在 ${retryDelay/1000} 秒后重试...`);
      setTimeout(init, retryDelay);
    } else {
      console.log('达到最大重试次数，停止重连');
      showFailToast("聊天服务连接失败，请刷新页面重试");
    }
  };
  
  // 错误事件
  ws.onerror = function (error) {
    console.error('WebSocket错误:', error);
    console.error('WebSocket URL:', ws.url);
    console.error('WebSocket状态:', ws.readyState);
    
    // 添加更详细的错误信息和处理
    console.log('尝试诊断WebSocket连接问题...');
    
    // 检查URL格式
    if (!ws.url.includes('/websocket')) {
      console.error('WebSocket URL格式可能不正确，应包含/websocket路径');
    }
    
    // 检查连接状态
    const states = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
    console.log('WebSocket连接状态:', states[ws.readyState] || '未知');
    
    // 检查网络连接
    console.log('检查网络连接状态...');
    
    // 不要立即显示错误，因为可能会自动尝试重连
    if (stats.value.reconnectAttempts && stats.value.reconnectAttempts > 2) {
      showFailToast("聊天连接发生错误，尝试重新连接中");
    }
  };
  
  // 连接成功事件
  ws.onopen = function() {
    console.log('WebSocket连接已打开，URL:', ws.url);
    // 重置重连计数
    stats.value.reconnectAttempts = 0;
    startHeartbeat();
  };
}

const send = () => {
  if (stats.value.chatUser.id === 0 && stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
    showFailToast("聊天对象无效");
    return;
  }
  
  if (stats.value.chatUser.id === stats.value.user.id && stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT) {
    showFailToast("不能给自己发信息")
    return;
  }
  
  if (!stats.value.text.trim()) {
    showFailToast("请输入内容")
    return;
  }
  
  if (typeof (WebSocket) == "undefined") {
    showFailToast("您的浏览器不支持WebSocket")
    return;
  }
  
  if (!socket || socket.readyState !== WebSocket.OPEN) {
    showFailToast("聊天连接已断开，请刷新页面重试");
    return;
  }
  
  try {
    // 获取当前时间 - 使用与后端一致的格式
    const now = new Date();
    // 格式化为"yyyy年MM月dd日 HH:mm:ss"，与后端保持一致
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const hour = now.getHours().toString().padStart(2, '0');
    const minute = now.getMinutes().toString().padStart(2, '0');
    const second = now.getSeconds().toString().padStart(2, '0');
    
    const formattedTime = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
    console.log('格式化的消息时间:', formattedTime);
    
    // 构建消息对象
    let message = {
      fromId: stats.value.user.id,
      toId: stats.value.chatType === stats.value.chatEnum.PRIVATE_CHAT ? stats.value.chatUser.id : 0,
      text: stats.value.text.trim(),
      chatType: Number(stats.value.chatType), // 确保chatType是数字类型
      teamId: stats.value.chatType === stats.value.chatEnum.TEAM_CHAT ? stats.value.team.teamId : 0,
    }
    
    console.log('准备发送消息:', message);
    
    // 通过WebSocket发送消息
    socket.send(JSON.stringify(message));
    console.log('消息已通过WebSocket发送');
    
    // 添加到本地消息列表的完整消息对象
    const localMessage = {
      ...message,
      createTime: formattedTime,  // 使用与后端一致的格式
      isMy: true,
      fromUser: { ...stats.value.user }  // 确保复制用户对象，而不是引用
    };
    
    console.log('添加到本地消息列表:', localMessage);
    
    // 按时间顺序插入消息
    insertMessageInOrder(localMessage);
    
    // 清空输入框并滚动到底部
    stats.value.text = '';
    nextTick(() => {
      scrollToBottom();
    });
  } catch (error) {
    console.error('发送消息时出错:', error);
    showFailToast('发送消息失败，请重试');
  }
}

/**
 * 安全地解析各种可能的时间格式
 * @param {string} timeStr 时间字符串
 * @returns {number} 时间戳毫秒数
 */
const parseTimeToMs = (timeStr) => {
  if (!timeStr) return 0;
  
  try {
    // 处理中文格式的时间："2023年5月15日 12:30:45"
    if (typeof timeStr === 'string' && timeStr.includes('年')) {
      const parts = timeStr.split(' ');
      if (parts.length === 2) {
        const datePart = parts[0];
        const timePart = parts[1];
        
        // 提取日期部分
        const yearMatch = datePart.match(/(\d+)年/);
        const monthMatch = datePart.match(/(\d+)月/);
        const dayMatch = datePart.match(/(\d+)日/);
        
        const year = yearMatch ? parseInt(yearMatch[1]) : new Date().getFullYear();
        const month = monthMatch ? parseInt(monthMatch[1]) - 1 : 0; // 月份从0开始
        const day = dayMatch ? parseInt(dayMatch[1]) : 1;
        
        // 提取时间部分
        const timeArr = timePart.split(':');
        const hour = timeArr.length > 0 ? parseInt(timeArr[0]) : 0;
        const minute = timeArr.length > 1 ? parseInt(timeArr[1]) : 0;
        const second = timeArr.length > 2 ? parseInt(timeArr[2]) : 0;
        
        return new Date(year, month, day, hour, minute, second).getTime();
      }
    }
    
    // 标准格式的时间
    return new Date(timeStr).getTime();
  } catch (e) {
    console.error('无法解析时间:', timeStr, e);
    return 0;
  }
};

/**
 * 按时间顺序插入消息到指定数组
 * @param {Object} message 要插入的消息对象
 * @param {Array} array 目标数组
 */
const insertMessageIntoArray = (message, array) => {
  const msgTime = parseTimeToMs(message.createTime);
  
  // 如果数组为空，直接添加
  if (array.length === 0) {
    array.push(message);
    return;
  }
  
  // 如果新消息比最后一条消息还要新，直接添加到末尾(最常见的情况)
  const lastMsg = array[array.length - 1];
  const lastMsgTime = parseTimeToMs(lastMsg.createTime);
  
  if (msgTime >= lastMsgTime) {
    array.push(message);
    return;
  }
  
  // 如果新消息比第一条消息还要早，插入到开头
  const firstMsg = array[0];
  const firstMsgTime = parseTimeToMs(firstMsg.createTime);
  
  if (msgTime <= firstMsgTime) {
    array.unshift(message);
    return;
  }
  
  // 使用二分查找找到合适的位置插入
  let left = 0;
  let right = array.length - 1;
  
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const midTime = parseTimeToMs(array[mid].createTime);
    
    if (midTime < msgTime) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }
  
  // 在left位置插入新消息
  array.splice(left, 0, message);
};

/**
 * 按时间顺序插入消息到消息列表
 * @param {Object} message 要插入的消息对象
 */
const insertMessageInOrder = (message) => {
  insertMessageIntoArray(message, stats.value.messages);
}

// 滚动到底部的函数
const scrollToBottom = () => {
  nextTick(() => {
    const chatRoomEl = chatRoom.value;
    if (chatRoomEl) {
      chatRoomEl.scrollTop = chatRoomEl.scrollHeight;
    }
  });
}

const onClickLeft = () => {
  router.back();
}

const showUser = (id) => {
  if (!id) return;
  router.push({
    path: `/user/${id}`,
  });
}
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 46px);
  overflow-y: auto;
  background-color: #f7f7f7;
  position: relative;
}

.content {
  padding-top: 22px;
  padding-bottom: 65px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.message {
  display: flex;
  align-items: flex-start;
  margin: 15px 10px;
  width: calc(100% - 20px);
  box-sizing: border-box;
  position: relative;
}

.self {
  align-self: flex-end;
  flex-direction: row;
  justify-content: flex-end;
  padding-right: 5px;
  max-width: 80%;
}

.other {
  align-self: flex-start;
  max-width: 80%;
}

.avatar {
  align-self: flex-start;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  margin-left: 10px;
  object-fit: cover;
  border: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.self-avatar {
  margin-right: 10px;
  margin-left: 5px;
}

.username {
  font-size: 12px;
  color: #999;
  padding-bottom: 4px;
  white-space: nowrap;
  overflow: visible;
}

.right-align {
  text-align: right;
  margin-right: 0;
  margin-left: 0;
}

.right-content {
  align-items: flex-end;
  margin-right: 10px;
  margin-left: 0;
  max-width: calc(100% - 55px);
}

.info {
  display: flex;
  flex-direction: column;
  max-width: calc(100% - 65px);
}

.text {
  padding: 12px;
  border-radius: 18px;
  background-color: #ffffff;
  word-wrap: break-word;
  word-break: break-all;
  margin: 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  line-height: 1.5;
}

.other .text {
  align-self: flex-start;
  border-top-left-radius: 4px;
}

.self .text {
  background-color: #0084ff;
  color: #fff;
  align-self: flex-end;
  border-top-right-radius: 4px;
}

.admin {
  background-color: #ffd6e7;
}

.input-area {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #ffffff;
  padding: 8px 0;
  box-shadow: 0 -1px 5px rgba(0,0,0,0.1);
}

.van-button--primary {
  margin-right: 10px;
}
</style>
